<script setup lang="ts">
import { uploadAPI } from '@/apis/common';
import { createEnterpriseAPI, editEnterpriseAPI, getIndustryListAPI, watchEnterpriseAPI } from '@/apis/enterprise';
import { type EnterpriseDetail, type EnterpriseParams, type Industry } from '@/types/enterprise';
import { ElMessage,type FormInstance,type FormRules, type UploadData, type UploadRawFile, type UploadRequestOptions, type UploadUserFile } from 'element-plus';
import { onMounted, ref, watch } from 'vue';
import { Upload, CircleCheck } from '@element-plus/icons-vue'
import { useRoute, useRouter } from 'vue-router';
// 参数
const addForm = ref<EnterpriseParams>({
  name: '', // 企业名称
  legalPerson: '', // 法人
  registeredAddress: '', // 注册地址
  industryCode: undefined, // 所在行业
  contact: '', // 企业联系人
  contactNumber: '', // 联系人电话
  businessLicenseUrl: '', // 营业执照url
  businessLicenseId: -1 // 营业执照id
})
// 校验
const addRoules = ref<FormRules<EnterpriseParams>>({
  name: [
    { required: true, message: '请输入企业名称', trigger: 'blur' },
    { min: 2, max: 20, message: '请输入2-20位企业名称', trigger: 'blur' }
  ],
  legalPerson: [
    { required: true, message: '请输入法人', trigger: 'blur' },
    { min: 2, max: 20, message: '请输入2-20位法人', trigger: 'blur' }
  ],
  registeredAddress: [
    { required: true, message: '请输入注册地址', trigger: 'blur' },
  ],
  industryCode: [
    { required: true, message: '请选择行业', trigger: 'change' }
  ],
  contact: [
    { required: true, message: '请输入企业联系人', trigger: 'blur' },
    { min: 2, max: 20, message: '请输入2-20位企业联系人', trigger: 'blur' }
  ],
  contactNumber: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  businessLicenseUrl: [
    { required: true, message: '请上传营业执照', trigger: 'blur' }
  ]
})

// 请求行业列表
const industryList = ref<Industry[]>([])
const getIndustryList = async () =>{
  const res = await getIndustryListAPI()
  industryList.value = res.data
  console.log(res.data)
}
onMounted(() => {
    getIndustryList()
})
// 上传图片
const ruleForm = ref<FormInstance>()
const fileList = ref<UploadUserFile[]>([])
const onUploadRequest = async (options: UploadRequestOptions) => {
    const fd = new FormData()
    fd.append('file', options.file)
    fd.append('type', 'businessLicense')
    const res = await uploadAPI(fd)
    addForm.value.businessLicenseId = res.data.id
    addForm.value.businessLicenseUrl = res.data.url
    ruleForm.value?.validateField('businessLicenseUrl')
    console.log(fileList.value)
    return res.data as UploadData
}
// 删除图片
const onRemove = (file: UploadUserFile) => {
    addForm.value.businessLicenseUrl = ''
    addForm.value.businessLicenseId = -1
    ruleForm.value?.validateField('businessLicenseUrl')
}
// 记录错题-------------------------------------------------
// watch(fileList, (val) => {
//     console.log(val)
//     if (val.length > 0) {
//         const newval = val[0].response as UploadData
//         addForm.value.businessLicenseUrl = newval?.url
//     } else {
//         addForm.value.businessLicenseUrl = ''
//         addForm.value.businessLicenseId = -1
//     }
//     ruleForm.value?.validateField('businessLicenseUrl')

// },{deep: true})

// 上传图片限制
const beforeUpload = (rawFile: UploadRawFile) => {
    if (rawFile.size > 5 * 1024 * 1024) {
        ElMessage.error('图片大小不能超过5M')
        return false;
    } else if (!['image/jpeg', 'image/png'].includes(rawFile.type)) {
        ElMessage.error('上传图片格式不正确')
        return false;
    } else {
        return true;
    }
}
// 重置表单 -------------------------------------
const resetFrom = () => {
    ruleForm.value?.resetFields()
}
// 提交表单
const submitLoading = ref(false)
const router = useRouter()
const onSubmit = async () => {
    try {
        if (!route.params.id) {
            // 提交
            submitLoading.value = true
            await ruleForm.value?.validate()
            await createEnterpriseAPI(addForm.value)
            ElMessage.success('添加成功')
            router.back()
        } else {
            // 编辑
            submitLoading.value = true
            await ruleForm.value?.validate()
            await editEnterpriseAPI(Number(route.params.id), addForm.value)
            ElMessage.success('编辑成功')
            router.back()
        }
    } catch (error) {
        submitLoading.value = false
    }
}

// 编辑 --- 获取企业详情 --- 回显数据
const route = useRoute()
const watchEnterprise = async () => {
    try {
        const res = await watchEnterpriseAPI(Number(route.params.id) as number)
        for (const key of Object.keys(addForm.value)){
            const typedKey = key as keyof EnterpriseParams;
            Reflect.set(addForm.value, typedKey, res.data[typedKey])
        }
        fileList.value = [{
            name: res.data.name,
            url: res.data.businessLicenseUrl,
            uid: res.data.id,
            status: 'success' // 设置状态为成功上传
        }]
    } catch (error) {
        setTimeout(() => {
            router.back()
        }, 1000)
    }
}
if (route.params.id) {
    watchEnterprise()
}
</script>


<template>
  <div class="add-enterprise">
    <header class="add-header">
      <el-page-header content="添加企业" @back="$router.back()" />
    </header>
    <main class="add-main">
      <div class="form-container">
        <div class="title">企业信息</div>
        <div class="form">
          <el-form ref="ruleForm" label-width="100px" :model="addForm" :rules="addRoules">
            <el-form-item label="企业名称" prop="name">
              <el-input v-model="addForm.name" />
            </el-form-item>
            <el-form-item label="法人" prop="legalPerson">
              <el-input v-model="addForm.legalPerson" />
            </el-form-item>
            <el-form-item label="注册地址" prop="registeredAddress">
              <el-input v-model="addForm.registeredAddress" />
            </el-form-item>
            <el-form-item label="所在行业" prop="industryCode">
                <el-select v-model="addForm.industryCode" clearable>
                    <el-option 
                        v-for="item in industryList" 
                        :key="item.industryCode" 
                        :value="item.industryCode"
                        :label="item.industryName"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="企业联系人" prop="contact">
              <el-input v-model="addForm.contact" />
            </el-form-item>
            <el-form-item label="联系电话" prop="contactNumber">
              <el-input v-model="addForm.contactNumber" />
            </el-form-item>
            <el-form-item label="营业执照" prop="businessLicenseUrl">
                <el-upload
                    class="upload-demo"
                    :http-request="onUploadRequest"
                    list-type="picture"
                    v-model:file-list="fileList"
                    limit="1"
                    :before-upload="beforeUpload"
                    :on-remove="onRemove"
                >
                    <el-button v-if="fileList.length === 0" type="primary" :icon="Upload">上传</el-button>
                    <el-button v-else type="success" disabled :icon="CircleCheck">已上传</el-button>
                    <template #tip>
                    <div class="el-upload__tip">
                        5M！ 混蛋
                    </div>
                    </template>
                </el-upload>
            </el-form-item>
          </el-form>
        </div>
        {{ addForm }}
      </div>
    </main>
    <footer class="add-footer">
      <div class="btn-container">
        <el-button @click="resetFrom" :disabled="$route.params.id">重置</el-button>
        <el-button @click="onSubmit" type="primary" :loading="submitLoading">确定</el-button>
      </div>
    </footer>
  </div>
</template>


<style scoped lang="scss">
.add-enterprise {
  background-color: #f4f6f8;
  height: 100vh;

  .add-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 20px;
    height: 64px;
    line-height: 64px;
    font-size: 16px;
    font-weight: bold;
    background-color: #fff;

    .left {
      span {
        margin-right: 4px;
      }

      .arrow {
        cursor: pointer;
      }
    }

    .right {
      text-align: right;
    }
  }

  .add-main {
    background: #f4f6f8;
    padding: 20px 130px;

    .form-container {
      background-color: #fff;

      .title {
        height: 60px;
        line-height: 60px;
        padding-left: 20px;
      }

      .form {
        margin-bottom: 20px;
        padding: 20px 65px 24px;

        .el-form {
          display: flex;
          flex-wrap: wrap;

          .el-form-item {
            width: 50%;
          }
        }
      }
    }
  }

  .add-footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    padding: 24px 50px;
    color: #000000d9;
    font-size: 14px;
    background: #fff;
    text-align: center;
  }
}
</style>